<template>
    <div class="app-detail">
        <list-layout class="material-container">
            <div slot="search">
                <el-form :model="queryParams" :inline="true" label-position="right" ref="queryForm" v-show="showSearch" label-width="130px">

                    <el-form-item :label="$t('material.materialName')" prop="materialName">
                        <el-select v-if="false" v-model="queryParams.factoryCode" :placeholder="$t('public.select_holder',{select_holder: $t('inspectionManagement.plantArea')})" style="width:100%;" filterable clearable size="small">
                            <el-option v-for="(item) in factoryList" :key="item.plantCode" :label="item.plantName" :value="item.plantCode" />
                        </el-select>
                        <el-input size="small" v-model="queryParams.materialName" :placeholder="$t('public.placeholder',{placeholder: $t('material.materialName')})" />
                    </el-form-item>
                    <el-form-item :label="$t('material.materialCode')" prop="materialCode">
                        <el-input size="small" v-model="queryParams.materialCode" :placeholder="$t('public.placeholder',{placeholder: $t('material.materialCode')})" />
                    </el-form-item>
                </el-form>
                <div style="display: flex; justify-content: center">
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("public.search") }}</el-button>
                    <el-button icon="el-icon-refresh" class="resectBtn" size="mini" @click="resetQuery">{{
            $t("public.reset")
            }}</el-button>
                </div>
            </div>
            <el-row :gutter="20" class="mb8">
                <el-col :span="6"><span class="title-info">{{ $t('transferRules.ruleCode')+'：'+ ruleData.ruleCode }}</span>
                </el-col>
                <el-col :span="6"><span class="title-info">{{ $t('transferRules.ruleName')+'：'+ ruleData.ruleName }}</span>
                </el-col>
                <el-col :span="6"><span class="title-info">{{ $t('inspectionStandards.division')+'：'+ ruleData.divisionName }}</span>
                </el-col>
            </el-row>
            <el-row :gutter="10">
                <el-col :span="11">
                    <div class="app-container">
                        <div class="container-header">
                            <div class="header-left"> {{ $t('transferRules.unusedMaterial') }} </div>
                        </div>
                        <div class="container-table">
                            <el-table class="table-fixed" :row-class-name="tableRowClassName" ref="unusedTable" :key="unusedKey" v-loading="unusedLoading" :height="tableHeight" border :data="unusedTableList" @selection-change="unusedTableSelectFN">
                                <el-table-column type="selection" width="55" fixed="left" align="center" :show-overflow-tooltip="true" />

                                <el-table-column :label="$t('material.materialCode')" sortable v-if="columns[0].visible" align="left" prop="materialCode" min-width="180" :show-overflow-tooltip="true" />
                                <el-table-column :label="$t('material.materialName')" sortable v-if="columns[0].visible" align="left" prop="materialName" min-width="180" :show-overflow-tooltip="true" />
                                <el-table-column :label="$t('formValidation.affiliatedFactoryArea')" sortable v-if="columns[0].visible" align="left" prop="plantName" min-width="180" :show-overflow-tooltip="true" />
                                <el-table-column :label="$t('basicData.materialType')" sortable v-if="columns[0].visible" align="left" prop="materialType" min-width="180" :show-overflow-tooltip="true" />

                            </el-table>

                            <pagination v-show="unusedTotal > 0" :total="unusedTotal" :page.sync="unusedQueryParams.pageNum" :limit.sync="unusedQueryParams.pageSize" @pagination="getUnusedList" layout="total, sizes, prev, pager, next, jumper" />
                        </div>
                    </div>

                </el-col>
                <el-col :span="2" class="middle-col">
                    <el-row class="mid-btn"><el-button type="primary" :disabled="!(usedIds.length>0)"
                        :loading="loading || unusedLoading || usedLoading" size="small" @click="handleChangeUsed(0)">
                        <i class="el-icon-arrow-left el-icon--left"></i>
                        {{ $t('btn.cancel') }}
                    </el-button></el-row>
                    <el-row class="mid-btn"><el-button type="primary" :disabled="!(unusedIds.length>0)"
                        :loading="loading || unusedLoading || usedLoading" size="small" @click="handleChangeUsed(1)">
                        {{ $t('btn.use') }}
                        <i class="el-icon-arrow-right el-icon--right"></i>
                    </el-button></el-row>
                </el-col>
                <el-col :span="11">
                    <div class="app-container">
                        <div class="container-header">
                            <div class="header-left">
                                {{ $t('transferRules.selectedMaterial') }}
                            </div>
                        </div>
                        <div class="container-table">
                            <el-table class="table-fixed" :row-class-name="tableRowClassName" ref="multipleTable" :key="incomingKey" v-loading="usedLoading" :height="tableHeight" border :data="usedTableList" @selection-change="usedTableSelectFN">
                                <el-table-column type="selection" width="55" fixed="left" align="center" :show-overflow-tooltip="true" />

                                <el-table-column :label="$t('material.materialCode')" sortable v-if="columns[0].visible" align="left" prop="materialCode" min-width="180" :show-overflow-tooltip="true" />
                                <el-table-column :label="$t('material.materialName')" sortable v-if="columns[0].visible" align="left" prop="materialName" min-width="180" :show-overflow-tooltip="true" />
                                <el-table-column :label="$t('formValidation.affiliatedFactoryArea')" sortable v-if="columns[0].visible" align="left" prop="factoryName" min-width="180" :show-overflow-tooltip="true" />
                                <el-table-column :label="$t('basicData.materialType')" sortable v-if="columns[0].visible" align="left" prop="materialType" min-width="180" :show-overflow-tooltip="true" />
                                <el-table-column v-if="false" :label="$t('public.opera')" fixed="right" align="center" width="60">
                                    <template slot-scope="scope">
                                        <div class="action-wrap">
                                            <table-body-btn type="delete" :name="$t('transferRules.delRules')" @click.native="handleView(scope)" />
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>

                            <pagination v-show="usedTotal > 0" :total="usedTotal" :page.sync="usedQueryParams.pageNum" :limit.sync="usedQueryParams.pageSize" @pagination="getUsedList" layout="total, sizes, prev, pager, next, jumper" />
                        </div>
                    </div>

                </el-col>
            </el-row>
        </list-layout>

        <div class="submit-footer" >
            <el-button icon="el-icon-close" size="small" class="drawer-close" @click.native="handleClose">{{$t('public.close')}}</el-button>
            <el-button v-if="false" icon="el-icon-close" size="small" class="drawer-close">{{$t('public.close')}}</el-button>
        </div>
    </div>
</template>

<script>
import {getType, refreshCache} from '@/api/basic/dict/type'
import {
  addNcr,
  editAcceptReturns,
  getAcceptReturns,
  getAudit,
  getAuditCheck,
  getAuditEcho,
  getCollectionCheck,
  getInspectionCheck,
  getMinFlawAll,
  getNCRDetail,
  getNcrReviewCheck,
  getPrintCheck,
  getReleaseApproval,
  getReleaseCheck,
  getReport,
  getReturn,
  getReview,
  incomingList,
} from '@/api/inspectionManagement/inspectionManagement'
import {mapGetters, mapState} from 'vuex'
import {listALLFactory} from '@/api/basic/factory'
import FileUpload from '@/components/FileUpload'
import printerDialog from '@/views/components/printerDialog'
import {listMaterialType} from '@/api/basic/materialtype'
import SelectUserDialog from '@/views/components/SelectUserDialog'
import {getToken} from '@/utils/auth'

import { getMaterialBindList, addMaterialBind, delMaterialBind, getTransferRulesInfo } from '@/api/inspectionManagement/transferRules'
import { getMateriaGroupList, editMaterialGourp } from '@/api/masterdata/material'

export default {
    name: 'editMaterial',
    dicts: [
        'NYIQC_SHEET_STATUS', //检验单状态
        'NYIQC_NCR_DECISION', //使用决策
        'NYIQC_BATCH',
        'NYIQC_NCR_QCLASS',
        'NYIQC_EXEMPTEDOASTATUS', //免检审批状态
        'NYIQC_EXEMPTED', //免检
        'NYIQC_AUDIT_RESULT',
    ],
    components: {
        FileUpload,
        printerDialog,
        SelectUserDialog,
    },
    data() {
        return {
            direction: 'rtl',
            factoryList: [],
            optionLoading: false,
            returnInspection: false,
            returnKey: 0,
            releaseForm: {
                release: '1',
            },
            releaseOpen: false,
            columns: [
                {
                    key: 0,
                    label: this.$t('inventoryManagement.factory'),
                    visible: true,
                },
                {
                    key: 1,
                    label: '检验单号',
                    visible: true,
                },
                {
                    key: 2,
                    label: this.$t('inventoryManagement.inspectionOrderstatus'),
                    visible: true,
                },
                {
                    key: 3,
                    label: this.$t('inventoryManagement.arrivalTime'),
                    visible: true,
                },
                {
                    key: 4,
                    label: this.$t('inspectionManagement.inspectionStartTime'),
                    visible: true,
                },
                {
                    key: 5,
                    label: '检验项进度',
                    visible: true,
                },
                {
                    key: 6,
                    label: 'MSL等级',
                    visible: true,
                },
                {
                    key: 7,
                    label: this.$t('inventoryManagement.materialNo'),
                    visible: true,
                },
                {
                    key: 8,
                    label: this.$t('inventoryManagement.materialName'),
                    visible: true,
                },
                {
                    key: 9,
                    label: '规格型号',
                    visible: true,
                },
                {
                    key: 10,
                    label: this.$t('inventoryManagement.supplierName'),
                    visible: true,
                },
                {
                    key: 11,
                    label: this.$t('inventoryManagement.batchQuantity'),
                    visible: true,
                },
                {
                    key: 12,
                    label: this.$t('inventoryManagement.unit'),
                    visible: true,
                },
                {
                    key: 13,
                    label: this.$t('inventoryManagement.judgmentResult'),
                    visible: true,
                },
                {
                    key: 14,
                    label: '检验员',
                    visible: true,
                },
                {
                    key: 15,
                    label: '描述',
                    visible: true,
                },
                {
                    key: 16,
                    label: this.$t('performanceManagement.reviewer'),
                    visible: true,
                },
                {
                    key: 17,
                    label: this.$t('inventoryManagement.realityAuditName'),
                    visible: true,
                },
                {
                    key: 18,
                    label: this.$t('performanceManagement.auditOpinion'),
                    visible: true,
                },
                {
                    key: 19,
                    label: this.$t('inspectionManagement.approvalReason'),
                    visible: true,
                },
                {
                    key: 20,
                    label: this.$t('inventoryManagement.useDecision'),
                    visible: true,
                },
                {
                    key: 21,
                    label: this.$t('inspectionManagement.inspectionEndtTime'),
                    visible: true,
                },
                {
                    key: 22,
                    label: this.$t('inventoryManagement.maturity'),
                    visible: true,
                },
                {
                    key: 23,
                    label: this.$t('inventoryManagement.inspectionBatchNo'),
                    visible: true,
                },
                {
                    key: 24,
                    label: this.$t(
                        'inspectionManagement.isInspectionExemption'
                    ),
                    visible: true,
                },
                {
                    key: 25,
                    label: this.$t('inventoryManagement.batch'),
                    visible: true,
                },
                {
                    key: 26,
                    label: this.$t('inventoryManagement.supplierNo'),
                    visible: true,
                },
                {
                    key: 27,
                    label: this.$t('inspectionManagement.isPass'),
                    visible: true,
                },
                {
                    key: 28,
                    label: this.$t('inspectionManagement.isInspection'),
                    visible: true,
                },
                {
                    key: 29,
                    label: this.$t('inspectionManagement.inspectionDuration'),
                    visible: true,
                },
                {
                    key: 30,
                    label: this.$t('inspectionManagement.standardDuration'),
                    visible: true,
                },
                {
                    key: 31,
                    label: this.$t('inventoryManagement.recheckSheet'),
                    visible: true,
                },
                {
                    key: 32,
                    label: '采购订单号',
                    visible: true,
                },
                {
                    key: 33,
                    label: '申请人',
                    visible: true,
                },

                {
                    key: 34,
                    label: '库位编号',
                    visible: true,
                },
                {
                    key: 35,
                    label: '库位名称',
                    visible: true,
                },
                {
                    key: 36,
                    label: '入库结果',
                    visible: true,
                },
            ],
            printerVisible: false,
            printerUsingDecision: null,
            addInspection: false,
            minFlawOptions: [],
            showSearch: true,
            tableHeight: 'calc(100vh - 308px)',
            printerId: null,
            previewModel: {},
            ncrRefresh: 0,
            ncrModel: {
                ncrType: 0,
            },
            factoryList: [],
            drawer: false,
            approvalOpen: false,
            printerOpen: false,
            flag: false,
            printerForm: {},
            viewModel: {
                isContain: '0',
            },
            editModel: {
                inspectionInformation: '0',
            },
            approvalModel: {
                auditResult: '0',
                auditNotifier: null,
                auditCause: '',
                initiatorDept: '',
                initiatorName: '',
            },
            selBtn: 1,
            // 按钮
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            stemList: [],
            // 总条数
            total: 0,
            // 字典表格数据
            incomingList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            selectRows: [],
            rowifInspect: '',
            // 查询参数
            queryParams: {
                // materialName: '',
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                dictName: [
                    {
                        required: true,
                        message: '字典名称不能为空',
                        trigger: 'blur',
                    },
                ],
                dictType: [
                    {
                        required: true,
                        message: '字典类型不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            fullscreen: false,
            oldVersionVisiable: false,
            incomingKey: 0,

            // 未应用 请求表单
            unusedQueryParams: {
                pageNum: 1,
                pageSize: 20,
                // ruleApply: 0
            },
            // 应用 请求表单
            usedQueryParams: {
                pageNum: 1,
                pageSize: 20,
                // ruleApply: 1
            },

            // 表格数据
            unusedTableList: [], // 未使用表格列表
            usedTableList: [], // 使用表格列表

            // 表格总行数
            unusedTotal: 0,
            usedTotal: 1,

            // 表格loading
            unusedLoading: false,
            usedLoading: false,

            // 表格key
            unusedKey: 0,
            usedKey: 0,

            // 表格选中数据
            unusedSelectRows: [],
            usedSelectRows: [],

            // 表格选中ids
            unusedIds: [],
            unusedCodes: [], // materialCodes
            usedIds: [],
            usedCodes: [],

            // ruleId: '', // 规则Id
            // ruleCode: '',   // 规则Code
            ruleData: {},   // 规则详情
        }
    },
    mounted() {
        this.getRuleInfo();
        this.getList();
        return

        let incomingColumns = JSON.parse(
            localStorage.getItem('incomingColumns')
        )
        if (incomingColumns) {
            this.columns = JSON.parse(incomingColumns)
        }
        if (this.$route.query.status) {
            this.queryParams.sheetStatus = [this.$route.query.status]
            // if (!this.$route.query.ncr) {
            //     if (this.$route.query.type !== 'history') {
            //         this.queryParams.inspectionTime = [
            //             this.getNowDate(),
            //             this.getNowDate(),
            //         ]
            //     }
            // }
        }
        if (this.$route.query.exceedTimeStauts) {
            this.queryParams.exceedTimeStauts =
                this.$route.query.exceedTimeStauts
        }
        if (this.$route.query.uniqueId) {
            this.queryParams.id = this.$route.query.uniqueId
        }
        if (this.$route.query.status === '') {
            this.queryParams.sheetStatus = []
        }
        this.getList()
        this.getFactoryList()
        this.getLocation()
    },
    activated() {
        this.getRuleInfo();
        this.getList();
        return

        if (this.$route.query.status) {
            this.queryParams.sheetStatus = [this.$route.query.status]
            // if (!this.$route.query.ncr) {
            //     if (this.$route.query.type !== 'history') {
            //         this.queryParams.inspectionTime = [
            //             this.getNowDate(),
            //             this.getNowDate(),
            //         ]
            //     }
            // }
            this.queryParams.exceedTimeStauts = undefined
        }
        if (this.$route.query.exceedTimeStauts) {
            this.queryParams.sheetStatus = ['9']
            this.queryParams.exceedTimeStauts =
                this.$route.query.exceedTimeStauts
        }
        if (this.$route.query.uniqueId) {
            this.queryParams.sheetStatus = ['9']
            this.queryParams.id = this.$route.query.uniqueId
            this.queryParams.exceedTimeStauts = undefined
        }
        if (this.$route.query.status === '') {
            this.queryParams.sheetStatus = []
        }
        this.getList()
        this.getLocation()
        this.getFactoryList()
    },

    computed: {
        ...mapGetters(['userId', 'name', 'deptName']),
        ...mapState({
            isFold: (state) => state.app.isFold,
        }),

        // 获取 ruleId && ruleCode && divisionId
        ruleId(){return this.$route.query.ruleId??''},
        ruleCode(){return this.$route.query.ruleCode??''},
        divisionId(){return this.$route.query.divisionId??''},
    },
    watch: {
        isFold(val) {
            if (val === true) {
                this.tableHeight = 'calc(100vh - 308px)'
            } else {
                this.tableHeight = 'calc(100vh - 466px)'
            }
        },
    },
    methods: {
        changeFlaw(item, scope, index) {
            this.ncrModel.voList[scope.$index].flawList[index].minFlawName =
                item.minFlawName
            this.ncrModel.voList[scope.$index].flawList[index].minFlawCode =
                item.minFlawCode
            this.ncrModel.voList[scope.$index].flawList[index].minFlawId =
                item.id
            console.log(item, '==============')
        },
        deleteFlaw(scope) {
            this.ncrModel.voList[scope.$index].flawList.splice(scope.$index, 1)
        },
        addFlaw(scope) {
            this.ncrModel.voList[scope.$index].flawList.push({
                minFlawNr: null,
                minFlawName: null,
                minFlawId: null,
                minFlawCode: null,
                classId: this.ids.join(','),
            })
        },
        getFactoryList() {
            listAllFactory().then((res) => {
                this.factoryList = res.data
            })
        },
        handleSave(row, index) {
            console.log('flag===', this.flag)
            if (this.flag) {
                return
            }
            this.flag = true
            editAcceptReturns(row)
                .then((res) => {
                    this.$nextTick(() => {
                        this.returnList[index] = res.data
                        this.returnKey++
                    })
                    this.flag = false
                    this.$modal.msgSuccess('操作成功!')
                })
                .catch((err) => {
                    this.returnList[index].storageFailure = err
                    this.flag = false
                })
        },
        returnChange(val, row, index) {
            this.returnList[index].acceptAmount = (
                parseFloat(row.batchAmount) - parseFloat(val)
            ).toFixed(0)
        },
        acceptChange(val, row, index) {
            this.returnList[index].returnAmount = (
                parseFloat(row.batchAmount) - parseFloat(val)
            ).toFixed(0)
        },
        handleReFixed(row) {
            getAcceptReturns({ id: row.id }).then((res) => {
                this.returnList = res.data

                this.returnInspection = true
            })
        },

        handleReleaseOpen() {
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.releaseOpen = true
        },
        submitRelease() {
            getReleaseApproval({
                id: this.ids[0],
                release: this.releaseForm.release,
            }).then((response) => {
                this.$modal.msgSuccess('操作成功!')
                this.releaseOpen = false
                this.getList()
            })
        },
        userDataCallback(userId) {
            this.approvalModel.auditNotifierId = userId
            this.$refs.approvalModel.validateField('auditNotifier')
        },
        formatAuditOpinion(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_AUDIT_RESULT.find((item) => {
                    return item.value === e
                })
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        incomingFileChange(e) {
            let ids = e.map((item) => item.id)
            console.log('-------', ids)
            if (ids.length) {
                this.approvalModel.fileId = ids.join(',')
            }
        },
        showSelect(e, materialType) {
            if (e) {
                this.optionLoading = true
                getMinFlawAll({}).then((res) => {
                    this.minFlawOptions = res.data
                    this.optionLoading = false
                })
            }
            console.log(e)
        },
        columnsCallback(incomingColumns) {
            console.log('incomingColumns', incomingColumns)
            localStorage.setItem(
                'incomingColumns',
                JSON.stringify(incomingColumns)
            )
            this.incomingKey++
        },
        materialTypeRemoteMethod(val, cb) {
            listMaterialType({ typeName: val }).then((res) => {
                cb(res.rows)
            })
        },
        handleMaterialTypeSelect(e, scope) {
            // this.dialogForm.materialType = e
            this.queryParams.materialMin = e.typeName
            this.$forceUpdate()
        },
        formatExemptedOaStatus(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_EXEMPTEDOASTATUS.find(
                    (item) => {
                        return item.value === e
                    }
                )
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        // 获取小缺陷
        getMinFlaw() {
            // getMinFlawAll().then((res) => {
            //     this.minFlawOptions = res.data
            // })
        },
        formatOrderStatus(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_SHEET_STATUS.find((item) => {
                    return item.value === e
                })
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        formatUsingDecision(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_NCR_DECISION.find((item) => {
                    return item.value === e
                })
                console.log(e)
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        formatUsingDecisionTag(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_NCR_DECISION.find((item) => {
                    return item.value === e
                })
                if (obj) {
                    if (obj.label === '合格接受') {
                        return 'greenTag'
                    } else if (obj.label === '不接受') {
                        return 'redTag'
                    } else {
                        return 'yellowTag'
                    }
                }
            } else {
                return ''
            }
        },
        // 检验单状态变色
        sheetColorChange(row) {
            switch (row.sheetStatus) {
                case '0':

                case '1':
                case '2':
                    return 'labelColor1'
                case '3':
                    return 'labelColor0'
                case '4':
                case '5':
                    return 'labelY'
                default:
                    if (row.sheetStatus) {
                        return 'labelColor1'
                    }
            }
        },
        oaStatusColorChange(status) {
            switch (status) {
                case '0':
                    return 'labelY'
                case '1':
                    return 'labelColor0'
                case '2':
                    return 'labelColor1'
            }
        },
        getLocation() {
            // listALLStemLocation().then((response) => {
            //     this.stemList = response.data
            // })
        },
        submitNcrForm() {
            let files = []
            if (this.ncrModel.file1) {
                files.push(this.ncrModel.file1)
            }
            if (this.ncrModel.file2) {
                files.push(this.ncrModel.file2)
            }
            let submitData = {
                ...JSON.parse(JSON.stringify(this.ncrModel)),
                flawBizType: 'FLAW_UPLOAD',
                specificationBizType: 'SPECIFICATION_UPLOAD',
                fileId: files.join(','),
            }
            submitData.voList.forEach((io) => {
                io.flawChoice = io.flawChoice ? io.flawChoice.join(';') : ''
            })
            delete submitData.file1
            delete submitData.file2
            addNcr(submitData)
                .then((response) => {
                    this.$modal.msgSuccess('提交成功')
                    this.addInspection = false
                    this.getList()
                })
                .catch(() => {})
        },
        changeStem(e, scope, index) {
            this.ncrModel.voList[scope.$index].stemVoList[index].stemName = e
            this.ncrRefresh = this.ncrRefresh + 1
        },
        changeStemNumber(e, scope, index) {
            this.ncrModel.voList[scope.$index].stemVoList[index].stemNumber = e
            this.ncrRefresh = this.ncrRefresh + 1
        },
        addStem(scope) {
            let stemVoList = scope.row.stemVoList
            console.log(this.ncrModel.voList[scope.$index].stemVoList)
            this.ncrModel.voList[scope.$index].stemVoList.push({})
            this.ncrRefresh = this.ncrRefresh + 1
        },
        deleteStem(scope, index) {
            if (this.ncrModel.voList[scope.$index].stemVoList.length === 1) {
                this.$modal.msgWarning('请至少保留一条遏制信息!')
                return
            }
            this.ncrModel.voList[scope.$index].stemVoList.splice(index, 1)
            this.ncrRefresh = this.ncrRefresh + 1
        },
        factoryChange(e) {
            let obj = this.factoryList.find((item) => {
                return item.factoryName === e
            })
            this.ncrModel.launchFactory = obj.factoryName
        },
        getFactoryList() {
            listALLFactory().then((res) => {
                this.factoryList = res.data
            })
        },
        drawerClose() {
            this.drawer = false
        },
        getNowDate() {
            var date = new Date()
            var y = date.getFullYear()
            var m = date.getMonth() + 1
            var d = date.getDate()
            //  当前日期
            return (
                y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d)
            )
        },
        /** 查询字典类型列表 */
        getListFN() {
            this.loading = true
            let params = { ...this.queryParams }
            // params.maturity = params.maturity && params.maturity.join(',')
            params.sheetStatus =
                params.sheetStatus && params.sheetStatus.join(',')
            if (params.inspectionTime && params.inspectionTime.length) {
                params.params.beginTime = params.inspectionTime[0]
                params.params.endTime = params.inspectionTime[1]
            } else {
                params.params.beginTime = ''
                params.params.endTime = ''
            }
            delete params.inspectionTime
            if (params.checkoutEndTime && params.checkoutEndTime.length) {
                params.params.endBeginTime = params.checkoutEndTime[0]
                params.params.endEndTime = params.checkoutEndTime[1]
            } else {
                params.params.endBeginTime = ''
                params.params.endEndTime = ''
            }
            delete params.checkoutEndTime
            incomingList(params).then((response) => {
                if (response.code == 200 && response.rows) {
                    this.incomingList = response.rows
                    let selectRows = [...this.selectRows]
                    console.log(
                        'selectRows==============================',
                        selectRows
                    )
                    if (selectRows.length > 0) {
                        setTimeout(() => {
                            this.incomingList.forEach((io) => {
                                selectRows.forEach((ko) => {
                                    console.log(
                                        'true=============================='
                                    )
                                    if (io.id === ko.id) {
                                        this.$refs.multipleTable.toggleRowSelection(
                                            io,
                                            true
                                        )
                                    }
                                })
                            })
                        }, 300)
                    }
                    this.total = response.total
                    this.loading = false
                    this.tableHeight = this.isFold
                        ? 'calc(100vh - 308px)'
                        : 'calc(100vh - 466px)'
                }
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                dictId: undefined,
                dictName: undefined,
                dictType: undefined,
                status: '0',
                remark: undefined,
            }

            this.resetForm('form')
            this.queryParams.sheetStatus = ['9']
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.queryParams.exceedTimeStauts = null
            this.queryParams.id = null
            this.resetForm('queryForm')
            this.handleQuery()
        },
        handleAddIncoming() {
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            getInspectionCheck({ id: this.ids[0] }).then((response) => {
                this.$router.push({
                    path: '/addIncoming/index/' + this.ids[0],
                    query: { ifInspect: this.rowifInspect },
                })
            })
        },
        handleNcr() {
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            let selectRows = [...this.selectRows]
            selectRows.forEach((io) => {
                io.inspectionId = io.id
                io.stemVoList = [{}]
            })
            console.log(this.selectRows)
            getNcrReviewCheck({ ids: this.ids.join(',') }).then((response) => {
                if (response.code === 200) {
                    getNCRDetail({ ids: this.ids.join(',') }).then(
                        (ncrData) => {
                            if (ncrData.code === 200) {
                                let voList = ncrData.data.voList
                                voList.forEach((element) => {
                                    element.stemVoList = [{}]
                                    element.flawChoice = element.flawChoice
                                        ? element.flawChoice.split(';')
                                        : element.flawChoice
                                    element.flawList = [
                                        {
                                            minFlawNr: null,
                                            minFlawName: null,
                                            minFlawId: null,
                                            minFlawCode: null,
                                            classId: this.ids.join(','),
                                        },
                                    ]
                                })
                                this.ncrModel = {
                                    voList: voList,
                                    whetherStem: '2',
                                    ncrType: ncrData.data.ncrType,
                                }

                                this.addInspection = true
                            }
                        }
                    )
                    this.getMinFlaw()
                }
            })
        },
        handlePrinter() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            getPrintCheck({ ids: this.ids.join(',') }).then((response) => {
                if (response.code === 200) {
                    this.printerOpen = true
                }
            })
        },

        handleReturn() {
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            getReturn({ id: this.ids[0] }).then((response) => {
                this.$modal.msgSuccess('退回成功!')
                this.getList()
            })
        },
        handleSelectUse(row) {
            this.$router.push({
                path: '/incomingDetail/selectUse/0',
                query: {
                    id: row.id,
                    materialCode: row.materialCode,
                    materialName: row.materialName,
                    supplierCode: row.supplierCode,
                    inspectionLotMark: row.inspectionLotMark,
                    lot: row.lot,
                    ncrProcessId: row.ncrProcessId,
                },
            })
        },
        handleAddtionRecording() {
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            getCollectionCheck({ id: this.ids[0] }).then((response) => {
                this.$router.push({
                    path: '/additionData/index/' + this.ids[0],
                })
            })
        },
        handlePass() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            getReleaseCheck({ ids: this.ids.join(',') }).then((response) => {
                this.$router.push({ path: '/pass/index/' + this.ids.join(',') })
            })
        },
        /** 新增按钮操作 */
        handleAdd() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.addInspection = true
        },
        handleReview() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.$modal
                .confirm(this.$t('formValidation.confirm'))
                .then(() => {
                    getReview({ ids: this.ids.join(',') }).then((response) => {
                        this.$modal.msgSuccess('操作成功!')
                        this.getList()
                    })
                })
                .catch(() => {})
        },
        handleApproval() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            getAuditCheck({ id: this.ids[0] }).then((response) => {
                getAuditEcho({ id: this.ids[0] }).then((response) => {
                    this.approvalModel = response.data
                    let auditCause = []
                    response.data.flawList.forEach((io) => {
                        auditCause.push(io.minFlawName)
                    })
                    this.auditCause = auditCause.join(';')
                })

                this.approvalOpen = true
            })
        },

        // 自定义行类名
        tableRowClassName({ row, rowIndex }) {
            // console.log('rowIndex', rowIndex, row)
            if (row.isHighLight === true) {
                // console.log('rowIndex', row)
                return 'rowHighLight' //若isHighLight为true，则使用“rowHighLight”样式
            } else {
                return ''
            }
        },


        // 表格多选框选中数据
        unusedTableSelectFN(selection){
            console.log('Unused选中：',selection)
            this.unusedSelectRows = selection
            this.unusedIds = selection.map(i=> i.materialId)
            this.unusedCodes = selection.map(i=> i.materialCode)
        },
        usedTableSelectFN(selection){
            console.log('Used选中：',selection)
            this.usedSelectRows = selection
            this.usedIds = selection.map(i=> i.id)
            this.usedCodes = selection.map(i=> i.materialCode)
        },


        // 多选框选中数据
        handleSelectionChange(selection) {
            console.log(selection)
            // if (selection.length === 0) {
            //     return
            // }
            this.selectRows = selection
            if (selection.length > 0) {
                this.rowifInspect = selection[0].ifInspect
            }
            this.ids = selection.map((item) => item.id)
            console.log('this.ids', this.ids)
            this.incomingList.forEach((io, index) => {
                console.log('includes', this.ids.includes(io.id))
                if (this.ids.includes(io.id)) {
                    io.isHighLight = true
                } else {
                    io.isHighLight = false
                }
            })
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const dictId = row.dictId || this.ids
            getType(dictId).then((response) => {
                this.form = response.data
                this.open = true
                this.title = '修改字典类型'
            })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.open = false
        },
        submitApproval: function () {
            this.approvalOpen = false
            let submitData = {
                ...this.approvalModel,
                realityAuditName: this.name,
                realityAuditId: this.userId,
                id: this.ids[0],
            }
            if (this.approvalModel.auditResult === '0') {
                delete submitData.auditResult
            }

            getAudit(submitData).then((response) => {
                this.$modal.msgSuccess('审核成功')
                this.getList()
            })
        },
        /** 发起检验提交 */
        submitAddForm: function () {
            this.$modal.msgSuccess('发起成功!')
            this.addInspection = false
        },
        submitPrinter: function () {
            this.$modal.msgSuccess('打印成功!')
            this.printerOpen = false
        },

        /** 查看按钮操作 */
        handleView(scope) {
            this.$router.push({ path: '/incomingDetail/index/' + scope.row.id })
        },
        /** 打印预览操作 */
        handlePrinterView(scope) {
            getReport({ id: scope.row.id }).then((res) => {
                let reportId = res.data ? res.data : '791117854038990848'
                let a = document.createElement('a')
                a.href =
                    process.env.VUE_APP_BASE_API +
                    '/jimu/jmreport/view/' +
                    reportId +
                    '?token=' +
                    getToken() +
                    '&id=' +
                    scope.row.id
                a.target = '_blank'
                a.style.display = 'none'
                document.body.appendChild(a)
                a.click()
                a.remove()
                // this.$router.push({
                //     path: '/incoming/printerPreview/' + scope.row.id,
                //     query: {
                //         usingDecision: scope.row.usingDecision,
                //     },
                // })
            })
        },
        /** 编辑按钮操作 */
        handleEdit(row) {
            this.drawer = true
        },
        /** 关闭抽屉操作 */
        handleClose(row) {
            // this.drawer = false
            this.$router.go(-1)
        },
        /** 导出按钮操作 */
        handleExport() {
            let params = { ...this.queryParams }
            params.sheetStatus = params.sheetStatus.join(',')
            // params.maturity = params.maturity.join(',')
            if (params.inspectionTime && params.inspectionTime.length) {
                params.params.beginTime = params.inspectionTime[0]
                params.params.endTime = params.inspectionTime[1]
            } else {
                params.params.beginTime = ''
                params.params.endTime = ''
            }
            delete params.inspectionTime
            if (params.checkoutEndTime && params.checkoutEndTime.length) {
                params.params.endBeginTime = params.checkoutEndTime[0]
                params.params.endEndTime = params.checkoutEndTime[1]
            } else {
                params.params.endBeginTime = ''
                params.params.endEndTime = ''
            }
            delete params.checkoutEndTime
            this.download(
                'ny-iqc/incomingInspection/export',
                {
                    ...params,
                },
                `type_${new Date().getTime()}.xlsx`
            )
        },
        handleExportTemplate() {
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.download(
                'ny-iqc/incomingInspection/exportById?id=' + this.ids[0],
                {},
                `type_${new Date().getTime()}.xlsx`
            )
        },
        handleExportDetail() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.download(
                'ny-iqc/incomingInspection/exportDetails?ids=' +
                    this.ids.join(','),
                {},
                `type_${new Date().getTime()}.xlsx`
            )
        },
        /** 刷新缓存按钮操作 */
        handleRefreshCache() {
            refreshCache().then(() => {
                this.$modal.msgSuccess('刷新成功')
            })
        },
        imgFileChange1(e) {
            let ids = e.map((item) => item.id)
            console.log('-------', ids)
            if (ids.length) {
                this.ncrModel.file1 = ids.join(',')
            }
        },
        imgFileChange2(e) {
            let ids = e.map((item) => item.id)
            if (ids.length) {
                this.ncrModel.file2 = ids.join(',')
            }
        },

        // 获取未使用 物料列表
        getUnusedList(){
            this.unusedLoading = true
            let params = {
                ...this.queryParams,
                ...this.unusedQueryParams,
                divisionId: this.divisionId,
            }
            getMateriaGroupList(params).then(res=>{
                console.log('未使用回调',res)
                this.unusedTableList = res.rows ?? []
                this.unusedTotal = res.total ?? 0
            }).finally(()=>{
                this.unusedLoading = false
            })
        },
        // 获取 使用 物料列表
        getUsedList(){
            this.usedLoading = true
            let params = {
                ...this.queryParams,
                ...this.usedQueryParams,
                ruleCode: this.ruleCode,
                //divisionId: this.divisionId,//已选择物料
            }
            getMaterialBindList(params).then(res=>{
                console.log('使用回调',res)
                this.usedTableList = res?.rows ?? []
                this.usedTotal = res?.total ?? 0
            }).finally(()=>{
                this.usedLoading = false
            })
        },
        async handleChangeUsed(ruleApply){
            console.log('应用转换')
            this.loading=true
            let materialList =ruleApply==1 ?this.unusedSelectRows:this.usedSelectRows
            materialList = materialList.map(it=>{
                return {
                    materialCode:it.materialCode,
                    plantCode:it.plantCode?it.plantCode:it.factoryCode
                }
            })
            let groupRes = await editMaterialGourp({
                ruleApply,
                materialList
            })
            console.log('调用应用转换事件 ',groupRes)
            if(groupRes.code == 200) {

                if(ruleApply == "1"){ // 应用 ==> 新增
                    let params = this.unusedSelectRows.map(i=>{
                        i.ruleCode = this.ruleCode
                        return i
                    })
                    await addMaterialBind(params).then(resp=>{
                        console.log('物料',resp)
                    })
                } else { // 未应用 ==> 删除
                    console.log('应用ids',this.usedIds)
                    await delMaterialBind(this.usedIds.join(',')).then(resp=>{
                        console.log('物料',resp)
                    })
                }

                // 新
                // 重置并获取数据
                // this.reset
                this.getList()
                this.loading=false
            }
             this.loading=false
        },
        // 获取所有表格数据
        getList(){
            this.getUnusedList();
            this.getUsedList();
        },
        // 清空表格选中的行
        cleanSelectFn(tableRef){
            if(tableRef){
                this.$refs[tableRef]?.clearSelection()
            }
        },

        /** 获取规则详情  */
        getRuleInfo(){
            getTransferRulesInfo(this.ruleId).then(res=>{
                console.log('获取规则详情',res)
                if(res.code == 200 && res.data.id == this.ruleId) this.ruleData = res.data
            })
        }

    },
}
</script>
<style lang="scss" scoped>@import './index.scss';</style>
